import CryptoJS from 'crypto-js';

const KP = {
    // 秘钥
    key: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345678',
    // 偏移量
    iv: '1234567890'
};

/**
 * AES加密
 * @param data
 * @param key
 * @param iv
 */
const getAesStting = (data, key, iv) => {
    key = CryptoJS.enc.Utf8.parse(key);
    iv = CryptoJS.enc.Utf8.parse(iv);
    let encrypted = CryptoJS.AES.encrypt(data, key, {iv, node: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
    return encrypted.toString();
};

/**
 * AES解密
 * @param encrypted
 * @param key
 * @param iv
 * @returns {string}
 */
const getDAesString = (encrypted, key, iv) => {
    key = CryptoJS.enc.Utf8.parse(key);
    iv = CryptoJS.enc.Utf8.parse(iv);
    let decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv, node: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
    return decrypted.toString(CryptoJS.enc.Utf8);
};

// AES 对称秘钥加密
const AES = {
    en: (data) => getAesStting(data, KP.key, KP.iv),
    de: (data) => getDAesString(data, KP.key, KP.iv),
};

// BASE64
const BASE64 = {
    en: (data) => CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data)),
    de: (data) => CryptoJS.enc.Base64.parse(data).toString(CryptoJS.enc.Utf8),
};

// SHA256
const SHA256 = (data) => {
    return CryptoJS.SHA256(data).toString();
};

// MD5
const MD5 = (data) => {
    return CryptoJS.MD5(data).toString();
};

/**
 * 签名
 * @param token 身份令牌
 * @param timestamp 签名时间戳
 * @param data 签名数据
 * @returns {*}
 */
const SIGN = (token, timestamp, data) => {
    // 签名格式： timestamp + token + data(字典升序)
    let ret = [];
    for (let it in data) {
        let val = data[it];
        if (typeof val === 'object' && //
            (!(val instanceof Array) || (val.length > 0 && (typeof val[0] === 'object')))) {
            val = JSON.stringify(val);
        }
        ret.push(it + val);
    }
    // 字典升序
    ret.sort();
    let signsrc = timestamp + token + ret.join('');
    return MD5(signsrc);
};

export {AES, BASE64, SHA256, MD5, SIGN};
